from flask import Blueprint, request, g, session, jsonify
from Logger import logger
from utils import MyResponse, handle_exception, handle_success, to_lower_camel_case
import jwt
import datetime
import time
import bcrypt
from db_handler import db_handler

userManagement = Blueprint('userManagement', __name__)


# 查询用户信息
"""
传参:loginname、 status、 pageNum、 pageSize
返回:
"list": [
            {
                "department": "远光软件",
                "enable": 0,
                "id": 1,
                "login_name": "user",
                "user_name": "共享用户"
            },
"total": 3
    },
"""
@userManagement.route('/getAllUsers', methods=['POST'])
def get_all_users():
    try:
        # 获取请求参数
        params = request.json
        login_name = params.get("loginName", "")
        enable = params.get("enable", "")
        pageNum = int(params.get("pageNum", 1))  # 默认第一页
        pageSize = int(params.get("pageSize", 20))  # 默认每页20条


        # 构建查询语句
        select_query = "SELECT * FROM user WHERE (login_name LIKE %s AND enable LIKE %s) LIMIT %s, %s"
        start_index = (pageNum - 1) * pageSize
        login_name_like = f"%{login_name}%"
        user_status_like = f"%{enable}%"

        users_data = db_handler.execute_query(select_query, (login_name_like, user_status_like, start_index, pageSize))

        # 移除每个用户记录中的 password 和 is_admin 字段
        for user in users_data:
            del user['password']

        # 将字典键从蛇形命名转换为小驼峰命名
        transformed_users_data = [
            {to_lower_camel_case(k): v for k, v in user.items()}
            for user in users_data
        ]

        # 获取总条目数
        count_query = "SELECT COUNT(*) as total FROM user WHERE (login_name LIKE %s AND enable LIKE %s)"
        total_count = db_handler.execute_query(count_query, (login_name_like,user_status_like))[0]['total']

        # 构造返回结果
        result = {
            "list": transformed_users_data,
            "total": total_count
        }

        return handle_success(result, "success")
    except Exception as err:
        return handle_exception(err, "程序异常")

# 激活用户
@userManagement.route('/enableUser', methods=['POST'])
def enable_user():
    try:
        # 获取请求参数
        params = request.json
        user_ids = params.get("id")  # 用户ID

        # 构建更新语句
        update_query = """
        UPDATE user SET enable = '1' WHERE id = %s
        """

        # 执行批量更新操作
        for user_id in user_ids:
           db_handler.update(update_query, (user_id,))
        return handle_success("success", "激活用户成功")

    except Exception as err:
        return handle_exception(err, "程序异常")

# 禁用用户
@userManagement.route('/disableUser', methods=['POST'])
def disable_user():
    try:
        # 获取请求参数
        params = request.json
        user_ids = params.get("id")  # 用户ID

        # 构建更新语句
        update_query = """
        UPDATE user SET enable = '0' WHERE id = %s
        """

        # 执行批量更新操作
        for user_id in user_ids:
           db_handler.update(update_query, (user_id,))


        return handle_success("success", "禁用用户成功")
    except Exception as err:
        return handle_exception(err, "程序异常")


"""
传参:	
    "loginname":"chenman",
	"username":"陈蔓",
	"password":"1234.abcd",
	"department":"性能实验室",
	"status":"1",
	"role":"0"
返回:success
"""
# 新增用户
@userManagement.route('/addUser', methods=['POST'])
def add_user():
    try:
        params = request.json
        # 参数验证
        required_fields = ['loginName', 'userName', 'password', 'department', "enable", "isAdmin"]
        if not all(field in params for field in required_fields):
            return handle_exception({"msg": "缺少必要的参数"}, "error")

        loginname = params['loginName']
        username = params['userName']
        password = params['password']
        department = params['department']
        enable = params['enable']
        is_admin = params['isAdmin']

        # 检查用户名是否存在
        check_query = "SELECT COUNT(*) as countNum FROM User WHERE login_name = %s"
        existing_count = db_handler.execute_query(check_query, (loginname,))[0]['countNum']

        if existing_count > 0:
            return handle_exception({"msg": "该用户名已被占用"}, "该用户名已被占用")

        # 密码加密
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

        # 插入用户信息
        insert_query = "INSERT INTO User (login_name, user_name, password, department, enable, is_admin) VALUES (%s, %s, %s, %s, %s, %s)"
        insert_params = (loginname, username, hashed_password, department, enable, is_admin)
        result = db_handler.insert(insert_query, insert_params)

        if result is None:
            return handle_exception({"msg": "数据库操作失败"}, "error")

        return handle_success({"msg": "用户新增成功"}, "success")
    except KeyError as e:
        return handle_exception({"msg": f"缺少参数：{str(e)}"}, "error")
    except Exception as err:  # 捕获异常
        return handle_exception(err, "程序异常")

# 编辑用户
@userManagement.route('/editUser', methods=['POST'])
def edit_user():
    try:
        params = request.json
        # 参数验证
        required_fields = ['loginName', 'userName',  'department', "enable", "isAdmin"]
        if not all(field in params for field in required_fields):
            return handle_exception({"msg": "缺少必要的参数"}, "error")

        id = params['id']
        loginname = params['loginName']
        username = params['userName']
        department = params['department']
        enable = params['enable']
        is_admin = params['isAdmin']

        update_query = 'UPDATE user SET login_name = %s,user_name = %s,department = %s,enable = %s,is_admin = %s WHERE id = %s'

        update_params = (loginname, username, department, enable, is_admin, id)
        result = db_handler.update(update_query, update_params)

        if result is None:
            return handle_exception({"msg": "用户信息编辑失败"}, "error")

        return handle_success({"msg": "用户信息编辑成功"}, "success")

    except KeyError as e:
        return handle_exception({"msg": f"缺少参数：{str(e)}"}, "error")
    except Exception as err:  # 捕获异常
        return handle_exception(err, "程序异常")

"""
传参:userid
返回:success
"""
# 删除用户
@userManagement.route('/deleteUser', methods=['POST'])
def delete_user():
    try:
        # 获取请求参数
        params = request.json
        user_ids = params.get("id")

        # 构建删除语句
        delete_query = "DELETE FROM user WHERE id = %s"

        # 执行批量删除操作
        for user_id in user_ids:
           db_handler.delete(delete_query, (user_id,))

        # 返回响应
        return handle_success("success", "删除用户成功")

    except Exception as err:
        return handle_exception(err, "程序异常")

"""
传参:userid newPassword
返回:success
"""
# 重置密码
@userManagement.route('/resetPassword', methods=['POST'])
def reset_password():
    try:
        # 获取请求参数
        params = request.json
        user_id = params.get("id")
        new_password = params.get("newPassword")

        hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
        # 构建更新密码的SQL语句
        update_query = "UPDATE User SET password = %s WHERE id = %s"

        # 执行更新操作
        update_params = (hashed_password, user_id)
        result = db_handler.update(update_query, update_params)

        if result is None or result == 0:
            return handle_exception({"msg": "密码更新失败"}, "error")

        return handle_success({"msg": "密码更新成功"}, "success")

    except Exception as err:
        return handle_exception(err, "程序异常")